package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.example.pojo.UmsRule;
import org.example.mapper.UmsRuleMapper;
import org.example.service.IUmsRuleRelateService;
import org.example.service.IUmsRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wy
 * @since 2023-10-04
 */
@Service
public class UmsRuleServiceImpl extends ServiceImpl<UmsRuleMapper, UmsRule> implements IUmsRuleService {

    @Resource
    UmsRuleMapper ruleMapper;

    @Resource
    IUmsRuleRelateService relateService;

    @Override
    public List<UmsRule> getAllParentRule(String name) {


        return null;
    }

    @Override
    public UmsRule getRuleByParent(List<String> names) {
        List<Integer> id = new ArrayList<>();
        for(String name : names){
            UmsRule rule = ruleMapper.selectByName(name);
            id.add(rule.getId());
        }

        Collections.sort(id);
        StringBuilder parentId = new StringBuilder();
        for(Integer i : id) {
            parentId.append(i).append(",");
        }

        String substring = parentId.substring(0,parentId.length() - 1);

        return ruleMapper.selectByParent(substring);
    }

    @Override
    public Object list(UmsRule rule) {
        // 如果 有name传过来 就按照name 模糊查询
        QueryWrapper<UmsRule> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(rule.getName())) {
            wrapper.like("name",rule.getName());
        }
        if(rule.getActive() !=null) {
            wrapper.eq("active",rule.getActive());
        }

        // 如果分页返回 IPage 如果不分页 返回 List
        if(rule.getWithPage() == 1) {
            return this.page(new Page<>(rule.getPageNo(),rule.getPageSize()),wrapper);
        } else {
            return this.list(wrapper);
        }
    }

    @Override
    public boolean batchdel(Integer[] ids) {
        List<Integer> list = new ArrayList<>(ids.length);
        Collections.addAll(list,ids);
        UmsRule rule = new UmsRule();
        rule.setActive(0);
        UpdateWrapper<UmsRule> wrapper = new UpdateWrapper<>();
        wrapper.in("id",list);
        for (Integer id : ids){
            relateService.updateByRuleId(id);
        }
        return this.update(rule,wrapper);
    }
}
